import {
  Card,
  Breadcrumb,
  Form,
  Button,
  Radio,
  Input,
  Upload,
  Space,
  message,
} from 'antd'
import { PlusOutlined } from '@ant-design/icons'
import { Link, useHistory, useParams } from 'react-router-dom'
import styles from './index.module.scss'

import { useState, useRef, useEffect } from 'react'

// 引入富文本编辑器
import ReactQuill from 'react-quill'
import 'react-quill/dist/quill.snow.css'

// 引入Channel组件
import { Channel } from '@/components/Channel'

import { useDispatch } from 'react-redux'
import { updateArticle, getArticleById } from '@/store/actions'

const Publish = () => {
  const dispatch = useDispatch()
  const history = useHistory()

  const [maxCount, setMaxCount] = useState(1)
  const fileListRef = useRef([])

  // 定义上传文件列表
  const [fileList, setFileList] = useState([])

  // 创建form实例
  const [form] = Form.useForm()

  // 获取路由参数
  const { id } = useParams()
  // 判断是否为编辑文章
  const isEdit = !!id

  // 获取文章详情
  useEffect(() => {
    const loadData = async () => {
      if (!isEdit) return
      try {
        const res = await dispatch(getArticleById(id))
        const { channel_id, content, images, title, type } = res
        form.setFieldsValue({
          channel_id,
          content,
          title,
          type,
        })
        const newList = images.map((image) => ({ url: image }))
        setFileList(newList)
        setMaxCount(type)
        fileListRef.current = newList
      } catch {}
    }
    loadData()
  }, [dispatch, id, isEdit, form])

  // 定义上传文件的change函数
  const onUploadChange = (info) => {
    const fileList = info.fileList.map((file) => {
      if (file.response) {
        return {
          url: file.response.data.url,
        }
      }
      return file
    })
    fileListRef.current = fileList
    setFileList(fileList)
  }

  // 切换图片类型
  const changeType = (e) => {
    const count = e.target.value
    setMaxCount(count)
    if (count === 1) {
      const newFileList = fileListRef.current[0] ? [fileListRef.current[0]] : []
      setFileList(newFileList)
    } else if (count === 3) {
      setFileList(fileListRef.current)
    }
  }

  // 封装发布和存为草稿
  const saveArticle = async (value, msg, isDraft) => {
    if (value.type !== fileList.length)
      return message.warn('封面数量与所选数量不匹配！')

    const { type, ...restValue } = value
    const data = {
      ...restValue,
      cover: {
        type,
        images: fileList.map((image) => image.url),
      },
    }
    if (isEdit) {
      data.id = id
    }

    try {
      await dispatch(updateArticle(data, isDraft, isEdit))
      message.success(msg, 0.7, () => {
        history.push('/home/article')
      })
    } catch {}
  }

  // 发布文章
  const uploadArticle = async (value) => {
    try {
      saveArticle(value, isEdit ? '编辑成功！' : '发布成功！', false)
    } catch {}
  }

  // 存为草稿
  const saveDraft = async () => {
    try {
      const value = await form.validateFields()
      saveArticle(value, '保存草稿成功！', true)
    } catch {}
  }

  return (
    <div className={styles.root}>
      <Card
        title={
          <Breadcrumb separator=">">
            <Breadcrumb.Item>
              <Link to="/home">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>
              {isEdit ? '编辑文章' : '发表文章'}
            </Breadcrumb.Item>
          </Breadcrumb>
        }
      >
        <Form
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 16 }}
          initialValues={{ type: 1, content: '' }}
          onFinish={uploadArticle}
          form={form}
        >
          <Form.Item
            label="标题"
            name="title"
            rules={[{ required: true, message: '请输入文章标题' }]}
          >
            <Input placeholder="请输入文章标题" style={{ width: 400 }} />
          </Form.Item>
          <Form.Item
            label="频道"
            name="channel_id"
            rules={[{ required: true, message: '请选择文章频道' }]}
          >
            <Channel width={400} />
          </Form.Item>

          <Form.Item label="封面">
            <Form.Item name="type">
              <Radio.Group onChange={changeType}>
                <Radio value={1}>单图</Radio>
                <Radio value={3}>三图</Radio>
                <Radio value={0}>无图</Radio>
                {/* <Radio value={-1}>自动</Radio> */}
              </Radio.Group>
            </Form.Item>
            {maxCount > 0 && (
              <Upload
                name="image"
                action="http://geek.itheima.net/v1_0/upload"
                multiple={maxCount === 3}
                maxCount={maxCount}
                listType="picture-card"
                className="avatar-uploader"
                fileList={fileList}
                onChange={onUploadChange}
                showUploadList
              >
                <div style={{ marginTop: 8 }}>
                  <PlusOutlined />
                </div>
              </Upload>
            )}
          </Form.Item>
          <Form.Item
            label="内容"
            name="content"
            rules={[{ required: true, message: '请输入文章内容' }]}
          >
            <ReactQuill
              className="publish-quill"
              theme="snow"
              placeholder="请输入文章内容"
            />
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 4 }}>
            <Space>
              <Button size="large" type="primary" htmlType="submit">
                {isEdit ? '编辑文章' : '发表文章'}
              </Button>
              <Button size="large" onClick={saveDraft}>
                存入草稿
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}

export default Publish
